# author: wuye

import logging

from jsonschema import ValidationError, validate

from .exceptions import InvalidJSON

logger = logging.getLogger(__name__)


def json_schema_validate(schema, *, is_get=False):
    def validate_func(func):
        def _func(self, request, *args, **kwargs):
            try:
                if not is_get:
                    validate(request.data, schema)
                else:
                    validate(request.query_params, schema)
            except ValidationError as e:
                logger.exception("Invalid jsonschema")
                raise InvalidJSON(e) from e
            else:
                return func(self, request, *args, **kwargs)
        return _func
    return validate_func




# 使用方法：
# 1. 首先安装jsonschema库：pip install jsonschema==3.2.0
# 2. 在视图文件中导入该文件的json_schema_validate函数
#    比如： from .validate import json_schema_validate
# 3. 在视图类中以装饰器的方式使用，比如：（注意：如果是get请求，需要增加is_get=True）
# class JobView(APIView):
#     @json_schema_validate({
#         "type": "object",
#         "properties": {
#             "file_path": {
#                 "type": "string",
#                 "pattern": r"^(?!/)"
#                            r"(?!(?:.*/)?\.\.(?:$|/))"
#                            r"[^\r\n]+$"
#             },
#             "line_num": {
#                 "type": "string",
#                 "pattern": r"^\d+$"
#             },
#             "lines": {
#                 "type": "string",
#                 "pattern": r"^\d+$"
#             },
#         },
#         "required": ["file_path", "line_num"],
#     }, is_get=True)
#     def get(self, request):
#         pass
# 
#     @json_schema_validate({
#         "type": "object",
#         "properties": {
#             "job_ids": {
#                 "type": "array",
#                 "items": {"type": ["integer"]}
#             }
#         },
#         "required": ["job_ids"]
#     })
#     def post(self, request):
#         pass